package com.txzt.gaea.business.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Validated
@RestController
@RequestMapping("/biz")
public class BusinessController {


    @RequestMapping(value = "/token", method = RequestMethod.POST)
    public Map<String,String> getToken(@RequestBody Map<String,String> param) {
        String url = "http://192.168.1.181:8282/login";
        RestTemplate restTemplate = new RestTemplate();

        MultiValueMap<String,Object> requestMap = new LinkedMultiValueMap<>();
        requestMap.add("loginUsername", param.get("name"));
        requestMap.add("loginPassword", param.get("password"));

        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url,requestMap,JSONObject.class);
        List<String> cookies = responseEntity.getHeaders().get("Set-Cookie");
        if (CollectionUtils.isEmpty(cookies)) {
            return null;
        }
        Map<String,String> map = new HashMap<>(1);
        for(String c:cookies){
            if (c.contains("token")) {
                System.out.println(c);
                String token = StringUtils.substringBetween(c,"token=",";");
                System.out.println(token);
                map.put("admin_token",token);
                return map;
            }
        }
        return null;
    }
}
